import { ref } from 'vue';

import { deserialize } from '@/plugins/reflect-metadata';
import type { ListState } from '@/types';

import {
  getCardList, getcardListAll, getCardListByType, searchCardByName,
} from '../api';
import CardItem from '../models/CardItem';
import CardList, { CardQuery } from '../models/CardList';

const useCardList = () => {
  const params = ref<CardQuery>(new CardQuery());

  const state = ref<ListState<CardItem>>({
    data: [],
    loading: false,
    total: 0,
  });

  const stateAll = ref<ListState<CardItem>>({
    data: [],
    loading: false,
    total: 0,
  });

  const fetchAllData = async () => {
    try {
      stateAll.value.loading = true;
      const { data } = await getcardListAll(params.value);
      const resultData = deserialize(data, CardList);
      stateAll.value.data = resultData.items;
      stateAll.value.total = resultData.total;
    } catch (error) {
      //
    } finally {
      stateAll.value.loading = false;
    }
  };

  const fetchData = async () => {
    try {
      state.value.loading = true;
      const { data } = await getCardList(params.value);
      const resultData = deserialize(data, CardList);
      state.value.data = resultData.items;
      state.value.total = resultData.total;
    } catch (error) {
      //
    } finally {
      state.value.loading = false;
    }
  };

  const fetchDataByType = async (code: string) => {
    try {
      state.value.loading = true;
      params.value.cardProductType = code;
      const { data } = await getCardListByType(params.value);
      const resultData = deserialize(data, CardList);
      state.value.data = resultData.items;
      state.value.total = resultData.total;
    } catch (error) {
      //
    } finally {
      state.value.loading = false;
    }
  };

  const fetchDataByName = async (name: string) => {
    try {
      state.value.loading = true;
      params.value.cardProductName = name;
      const { data } = await searchCardByName(params.value);
      const resultData = deserialize(data, CardList);
      state.value.data = resultData.items;
      state.value.total = resultData.total;
    } catch (error) {
      //
    } finally {
      state.value.loading = false;
    }
  };

  return {
    params,
    state,
    stateAll,
    fetchAllData,
    fetchData,
    fetchDataByType,
    fetchDataByName,
  };
};

export default useCardList;
